package cmd

import (
	"context"
	"fmt"
	grpc_auth "github.com/grpc-ecosystem/go-grpc-middleware/auth"
	"google.golang.org/grpc"
	"log"
	"os"
	"week13/api/proto"
	"week13/configs"
	"week13/errors"
)
var appConfig configs.AppConfig
func init() {
	var err error
	dir := "C:\\Users\\03\\Desktop\\training-camp\\week13\\configs\\json\\app.json"
	f, err := os.Open(dir)
	if err !=nil {
		panic(err)
	}
	defer f.Close()
	appConfigs := configs.LoadAppConfigs(f)
	appConfig = appConfigs["auth"]
}
//通过redis 鉴权
func AuthFunc() func(ctx context.Context) (context.Context,error) {
	return func(ctx context.Context) (context.Context, error) {
		token, err := grpc_auth.AuthFromMD(ctx, "bearer")
		log.Println("example token-----------",token)
		if err != nil {
			log.Println("middle token err:",err)
			return nil, err
		}
		conn, err := grpc.Dial(appConfig.Addr, grpc.WithInsecure())
		if err != nil {
			return ctx, err
		}
		defer conn.Close()
		client := proto.NewAuthSrvClient(conn)
		tokenReq := proto.AuthRequest{Token: token}
		tokenResp,err := client.Auth(ctx,&tokenReq)
		if err != nil {
			return ctx,nil
		}
		agentId := tokenResp.AgentId
		log.Println("agentId:",agentId)
		newCtx := context.WithValue(ctx,"agentId",agentId)
		return newCtx, nil
	}
}
//通过JWT 鉴权
func AuthJWT() func(ctx context.Context) (context.Context,error) {
	return func(ctx context.Context) (context.Context, error) {
		token, err := grpc_auth.AuthFromMD(ctx, "bearer")
		log.Println("example token-----------",token)
		if err != nil {
			log.Println("middle token err:",err)
			return nil, err
		}
		conn, err := grpc.Dial(appConfig.Addr, grpc.WithInsecure())
		if err != nil {
			return ctx, err
		}
		defer conn.Close()
		client := proto.NewAuthSrvClient(conn)
		tokenReq := proto.AuthRequest{Token: token}
		tokenResp,err := client.AdminAuth(ctx,&tokenReq)
		fmt.Println("token resp:",tokenResp)
		if err != nil {
			return ctx,err
		}
		if tokenResp.Code != 0 {
			return nil, errors.NewTokenFail()
		}
		uid := tokenResp.Uid
		log.Println("uid:",uid)
		newCtx := context.WithValue(ctx,"uid",uid)
		return newCtx, nil
	}
}


